<template>
  <el-card>
    <el-form :inline="true" class="form">
      <el-form-item label="用户名:" style="margin-bottom: 0px">
        <el-input placeholder="请输入用户名" v-model="keyword"></el-input>
      </el-form-item>
      <el-form-item style="margin-bottom: 0px">
        <el-button
          type="primary"
          size="default"
          :disabled="keyword.trim() ? false : true"
          @click="search"
          >搜索</el-button
        >
        <el-button size="default" @click="reset">重置</el-button>
      </el-form-item>
    </el-form>
  </el-card>
  <el-card style="margin: 10px 0px">
    <el-button type="primary" size="default" @click="addUser" v-has="`btn.User.add`"
      >添加</el-button
    >
    <el-button
      type="danger"
      size="default"
      :disabled="batchArr.length ? false : true"
      @click="deleteBatch"
      v-has="`btn.User.remove`"
      >批量删除</el-button
    >
    <el-table :data="userArr" border style="margin: 10px 0px" @selection-change="selectChange">
      <el-table-column type="selection" width="40" align="center"></el-table-column>
      <el-table-column label="#" type="index" width="60" align="center"></el-table-column>
      <el-table-column label="id" width="80" align="center" prop="id"></el-table-column>
      <el-table-column
        label="用户账号"
        width="170"
        align="center"
        prop="username"
        show-overflow-tooltip
      ></el-table-column>
      <el-table-column
        label="用户昵称"
        width="170"
        align="center"
        prop="name"
        show-overflow-tooltip
      ></el-table-column>
      <el-table-column
        label="用户角色"
        width="200"
        align="center"
        prop="roleName"
        show-overflow-tooltip
      ></el-table-column>
      <el-table-column
        label="创建时间"
        align="center"
        prop="createTime"
        show-overflow-tooltip
      ></el-table-column>
      <el-table-column
        label="更新时间"
        align="center"
        prop="updateTime"
        show-overflow-tooltip
      ></el-table-column>
      <el-table-column label="操作" width="300" align="center">
        <template #="{ row, $index }">
          <el-button
            type="primary"
            size="small"
            icon="User"
            @click="setRole(row)"
            v-has="`btn.User.assgin`"
            >分配角色</el-button
          >
          <el-button
            type="primary"
            size="small"
            icon="Edit"
            @click="updateUser(row)"
            v-has="`btn.User.update`"
            >编辑</el-button
          >
          <el-popconfirm
            width="300px"
            :title="`确定要删除账户 ${row.username} 吗？`"
            @confirm="deleteUser(row.id)"
          >
            <template #reference>
              <el-button type="primary" size="small" icon="Delete" v-has="`btn.User.remove`"
                >删除</el-button
              >
            </template>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      v-model:current-page="pageNo"
      v-model:page-size="pageSize"
      :page-sizes="[2, 3, 5, 10, 20, 50]"
      :background="true"
      layout="prev, pager, next, jumper, ->, sizes, total"
      :total="total"
      @current-change="getHasUsers"
      @size-change="handler"
    />
  </el-card>
  <!-- 抽屉结构：完成添加新的用户账号|更新已有的账号信息 -->
  <el-drawer v-model="drawer" :close-on-click-modal="false">
    <template #header>
      <h4>{{ userParams.id ? '更新用户' : '添加用户' }}</h4>
    </template>
    <template #default>
      <el-form :model="userParams" :rules="rules" ref="ruleFormRef">
        <el-form-item label="用户账号" prop="username">
          <el-input placeholder="请输入用户账号" v-model="userParams.username"></el-input>
        </el-form-item>
        <el-form-item label="用户昵称" prop="name">
          <el-input placeholder="请输入用户昵称" v-model="userParams.name"></el-input>
        </el-form-item>
        <el-form-item label="用户密码" prop="password" v-if="!userParams.id">
          <el-input placeholder="请输入用户密码" v-model="userParams.password"></el-input>
        </el-form-item>
      </el-form>
    </template>
    <template #footer>
      <div style="flex: auto">
        <el-button @click="cancel">取消</el-button>
        <el-button type="primary" @click="save(ruleFormRef)">确定</el-button>
      </div>
    </template>
  </el-drawer>

  <!-- 抽屉结构：分配角色 -->
  <el-drawer v-model="drawer1" :close-on-click-modal="false">
    <template #header>
      <h4>分配角色</h4>
    </template>
    <template #default>
      <el-form>
        <el-form-item label="用户账号">
          <el-input v-model="userParams.username" :disabled="true"></el-input>
        </el-form-item>
        <el-form-item label="角色列表">
          <el-checkbox
            v-model="checkAll"
            :indeterminate="isIndeterminate"
            @change="handleCheckAllChange"
          >
            全选
          </el-checkbox>
          <el-checkbox-group v-model="userRole" @change="handleCheckedCitiesChange">
            <el-checkbox v-for="(role, index) in allRole" :key="index" :label="role">
              {{ role.roleName }}
            </el-checkbox>
          </el-checkbox-group>
        </el-form-item>
      </el-form>
    </template>
    <template #footer>
      <div style="flex: auto">
        <el-button @click="drawer1 = false">取消</el-button>
        <el-button type="primary" @click="confirmClick">确定</el-button>
      </div>
    </template>
  </el-drawer>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import {
  reqUsersInfo,
  reqAddOrUpdateUser,
  reqAllRole,
  reqSetUserRole,
  reqRemoveUser,
  reqBatchUser
} from '@/api/acl/user'
import type {
  UserResponseData,
  Records,
  User,
  AllRoleResponseData,
  AllRole,
  SetRoleData
} from '@/api/acl/user/type'
import { ElMessage } from 'element-plus'
import type { FormInstance, FormRules } from 'element-plus'
//获取设置相关的小仓库
import useLayoutSettingStore from '@/store/modules/setting'

let layoutSettingStore = useLayoutSettingStore()

let pageNo = ref<number>(1)
let pageSize = ref<number>(5)
let total = ref<number>(0)
let userArr = ref<Records>([])

//定义响应式数据控制抽屉的显示与隐藏
let drawer = ref<boolean>(false)
let drawer1 = ref<boolean>(false)

//收集用户信息的响应式数据
let userParams = reactive<User>({
  username: '',
  name: '',
  password: ''
})

//定义收集用户输入的关键字
let keyword = ref<string>('')

const ruleFormRef = ref<FormInstance>()

//校验用户名字的回调函数
const validateUsername = (rule: any, value: any, callback: any) => {
  if (value.trim().length >= 5) {
    callback()
  } else {
    callback(new Error('用户的账户名字至少5位'))
  }
}

const validateName = (rule: any, value: any, callback: any) => {
  if (value.trim().length >= 2) {
    callback()
  } else {
    callback(new Error('用户的昵称至少2位'))
  }
}

const validatePassword = (rule: any, value: any, callback: any) => {
  if (value.trim().length >= 6) {
    callback()
  } else {
    callback(new Error('用户的密码至少6位'))
  }
}

//表单校验的规则对象
const rules = reactive<FormRules<typeof userParams>>({
  username: [{ required: true, validator: validateUsername, trigger: 'blur' }],
  name: [{ required: true, validator: validateName, trigger: 'blur' }],
  password: [{ required: true, validator: validatePassword, trigger: 'blur' }]
})

const getHasUsers = async (pager = 1) => {
  pageNo.value = pager
  let result: UserResponseData = await reqUsersInfo(pageNo.value, pageSize.value, keyword.value)
  if (result.code == 200) {
    total.value = result.data.total
    userArr.value = result.data.records
  }
}

onMounted(() => {
  getHasUsers()
})

//分页器下拉菜单的自定义事件的回调
const handler = () => {
  getHasUsers()
}

//添加用户按钮的回调
const addUser = () => {
  //先清空数据
  Object.assign(userParams, {
    id: 0,
    username: '',
    name: '',
    password: ''
  })
  //清空校验规则
  ruleFormRef.value?.clearValidate()

  //抽屉显示出来
  drawer.value = true
}

//更新已有的User
const updateUser = (row: User) => {
  Object.assign(userParams, row)
  //抽屉显示出来
  drawer.value = true
  //清空校验规则
  ruleFormRef.value?.clearValidate()
}

//确定按钮额度回调
const save = async (formEl: FormInstance | undefined) => {
  //先校验
  if (!formEl) return
  formEl.validate(async (valid) => {
    if (valid) {
      let result: any = await reqAddOrUpdateUser(userParams)
      if (result.code == 200) {
        drawer.value = false
        ElMessage({
          type: 'success',
          message: userParams.id ? '更新成功！' : '添加成功！'
        })
        if (userParams.id) {
          keyword.value = ''
        }
        getHasUsers(userParams.id ? pageNo.value : 1)
        //每次更新完用户信息以后，刷新页面
        if (userParams.id) {
          //浏览器自动刷新一次
          window.location.reload()
        }
      } else {
        drawer.value = false
        ElMessage({
          type: 'error',
          message: userParams.id ? '更新失败！' : '添加失败！'
        })
      }
    } else {
      console.log('error submit!')
    }
  })
}
//取消按钮的回调
const cancel = () => {
  drawer.value = false
}

//分配角色按钮的回调
const setRole = async (row: User) => {
  //存储已有的用户信息
  Object.assign(userParams, row)
  let result: AllRoleResponseData = await reqAllRole(userParams.id as number)
  if (result.code == 200) {
    allRole.value = result.data.allRolesList
    userRole.value = result.data.assignRoles
    //抽屉显示出来
    drawer1.value = true
  }
}

//分配角色抽屉中，全选复选框收集数据：是否全选
const checkAll = ref<boolean>(false)
const isIndeterminate = ref<boolean>(true)
//存储全部角色的数据
let allRole = ref<AllRole>([])
const userRole = ref<AllRole>([])

const handleCheckAllChange = (val: boolean) => {
  userRole.value = val ? allRole.value : []
  isIndeterminate.value = false
}

const handleCheckedCitiesChange = (value: string[]) => {
  const checkedCount = value.length
  checkAll.value = checkedCount === allRole.value.length
  isIndeterminate.value = checkedCount > 0 && checkedCount < allRole.value.length
}

//确定按钮的回调（分配角色中的）
const confirmClick = async () => {
  //收集参数
  let data: SetRoleData = {
    userId: userParams.id as number,
    roleIdList: userRole.value.map((item) => {
      return item.id as number
    })
  }

  let result: any = await reqSetUserRole(data)
  if (result.code == 200) {
    ElMessage({
      type: 'success',
      message: '分配角色成功！'
    })
    //关闭抽屉
    drawer1.value = false
    //重新捞取数据
    getHasUsers(pageNo.value)
  } else {
    ElMessage({
      type: 'error',
      message: '分配角色失败！'
    })
  }
}

//删除某一个用户
const deleteUser = async (userId: number) => {
  let result: any = await reqRemoveUser(userId)
  if (result.code == 200) {
    ElMessage({
      type: 'success',
      message: '删除成功！'
    })
    getHasUsers(userArr.value.length > 1 ? pageNo.value : pageNo.value - 1)
  } else {
    ElMessage({
      type: 'error',
      message: '删除失败！'
    })
  }
}

//装备一个数组存储批量删除的用户
let batchArr = ref<number[]>([])

//table复选框勾选的时候会触发的事件
const selectChange = (newSelection: any[]) => {
  batchArr.value = newSelection.map((item) => {
    return item.id
  })
}

//批量删除按钮的回调
const deleteBatch = async () => {
  let result: any = await reqBatchUser(batchArr.value)
  if (result.code == 200) {
    ElMessage({
      type: 'success',
      message: '删除成功！'
    })
    getHasUsers(userArr.value.length - batchArr.value.length > 0 ? pageNo.value : pageNo.value - 1)
  } else {
    ElMessage({
      type: 'error',
      message: '删除失败！'
    })
  }
}

//搜索按钮的回调
const search = () => {
  //根据关键字获取相应的用户数据
  getHasUsers()
  //清空关键字
  // keyword.value = ''
}

//重置按钮
const reset = () => {
  layoutSettingStore.refresh = !layoutSettingStore.refresh
}
</script>

<style lang="scss" scoped>
.form {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
</style>
